package cn.huaqingcheng.tool.core;

import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * ReflectionTool
 */
@SuppressWarnings("unused")
public interface ReflectionTool {

    /**
     * 查找给定类型实现的第一个接口的类型参数
     *
     * @param clazz 待查找类型
     * @return 指定类型实现的接口的类型参数, 或者 null
     */
    @Nullable
    @Contract(value = "null -> null", pure = true)
    static Class<Object> getFirstGenericType(@Nullable Class<?> clazz) {
        if (clazz == null) {
            return null;
        }
        Class<Object> superClassArg = getGenericType(clazz.getGenericSuperclass());
        if (superClassArg != null) {
            return superClassArg;
        }
        for (Type type : clazz.getGenericInterfaces()) {
            Class<Object> interfacesTypeArg = getGenericType(type);
            if (interfacesTypeArg != null) {
                return interfacesTypeArg;
            }
        }

        return null;
    }

    @SuppressWarnings("unchecked")
    private static Class<Object> getGenericType(Type type) {
        if (type instanceof ParameterizedType parameterizedType) {
            Type[] types = parameterizedType.getActualTypeArguments();
            if (types.length >= 1) {
                return (Class<Object>) types[0];
            }
        }
        return null;
    }

}
